package utils;

import entity.Emotion;
import entity.News;
import entity.NewsInfo;
import entity.Share;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.query.Query;


import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Created by 梅晨 on 2017/7/27.
 */
public class SqlUtil {
    private static Logger logger = Logger.getLogger(SqlUtil.class);


    /**
     * 获取一个数据库会话连接
     * @return
     */
    private Session getSession(){
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        return session;
    }

    public void insertNews(List<NewsInfo> news){
        Session session = getSession();
        String shql = "select s from " + NewsInfo.class.getName() + " s where s.date = ? and s.title = ?";
        int positive = 0,negative = 0;
        Transaction t = session.beginTransaction();
        //将每篇新闻及预测结果存入数据库
        for(NewsInfo newsInfo : news){
            try{
                if(newsInfo.getEmotion().equals("正向")){
                    positive++;
                }else {
                    negative++;
                }
                Query query = session.createQuery(shql);
                query.setParameter(0,newsInfo.getDate());
                query.setParameter(1,newsInfo.getTitle());
                if(query.uniqueResult() == null){
                    session.persist(newsInfo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        t.commit();
        //统计所有文章的情绪指数，存入数据库
        shql = "select e from " + Emotion.class.getName() + " e where e.category = ? and e.date = ?";
        String uhql = "update " + Emotion.class.getName() + " s set s.positive = ?,s.negative = ?,s.sum = ?,s.value = ? where s.date = ? and s.category = ?";
        Emotion emotion = new Emotion();
        emotion.setDate(new java.sql.Date(new java.util.Date().getTime()));
        emotion.setPositive(positive);
        emotion.setNegative(negative);
        emotion.setSum(positive + negative);
        emotion.setValue(positive * 100 / (positive + negative + 1));
        emotion.setCategory("总体");
        Transaction t2 = session.beginTransaction();
        //add 2017-08-15 在插入数据库前先查询，如果存在则更新
        Query query = session.createQuery(shql);
        query.setParameter(0,emotion.getCategory());
        query.setParameter(1,emotion.getDate());
        if(query.uniqueResult() != null){
            logger.info("数据库中已存在" + emotion.getCategory() + ":" + emotion.getDate() + ", " + "正在更新");
            Query query1 = session.createQuery(uhql);
            query1.setParameter(0,emotion.getPositive());
            query1.setParameter(1,emotion.getNegative());
            query1.setParameter(2,emotion.getSum());
            query1.setParameter(3,emotion.getValue());
            query1.setParameter(4,emotion.getDate());
            query1.setParameter(5,emotion.getCategory());
            query1.executeUpdate();
        }else {
            session.persist(emotion);
        }
        t2.commit();
        session.close();
    }

    public void insertEmotion(HashMap<String,Set<NewsInfo>> newsCtgyMap,HashMap<String,Integer> score){
        Session session = getSession();
        String shql = "select e from " + Emotion.class.getName() + " e where e.category = ? and e.date = ?";
        String uhql = "update " + Emotion.class.getName() + " s set s.positive = ?,s.negative = ?,s.sum = ?,s.value = ? where s.date = ? and s.category = ?";
        Transaction t = session.beginTransaction();
        for(String category : newsCtgyMap.keySet()){
            int positive = 0,negative = 0;
            for(NewsInfo newsInfo : newsCtgyMap.get(category)){
                if(newsInfo.getEmotion().equals("正向")){
                    positive++;
                }else {
                    negative++;
                }
            }
            Emotion emotion = new Emotion();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new java.util.Date());
            calendar.add(Calendar.DATE,0);
            emotion.setDate(new java.sql.Date(calendar.getTime().getTime()));
            emotion.setPositive(positive);
            emotion.setNegative(negative);
            emotion.setSum(positive + negative);
            int val = (positive + 1) * 100 / (positive + negative + 1);
            int val2 = 50;
            if(score.containsKey(category)){
                val2 = score.get(category);
            }
            val = (val + val2) / 2;
            emotion.setValue(val);
            emotion.setCategory(category);
            //add 2017-08-15 在插入数据库前先查询，如果存在则更新
            Query query = session.createQuery(shql);
            query.setParameter(0,category);
            query.setParameter(1,emotion.getDate());
            if(query.uniqueResult() != null){
                logger.info("数据库中已存在" + emotion.getCategory() + ":" + emotion.getDate() + ", " + "正在更新");
                Query query1 = session.createQuery(uhql);
                query1.setParameter(0,emotion.getPositive());
                query1.setParameter(1,emotion.getNegative());
                query1.setParameter(2,emotion.getSum());
                query1.setParameter(3,emotion.getValue());
                query1.setParameter(4,emotion.getDate());
                query1.setParameter(5,emotion.getCategory());
                query1.executeUpdate();
            }else {
                session.persist(emotion);
            }

        }
        t.commit();
        session.close();
    }

    public void insertShare(List<Share> shares){
        Session session = getSession();
        Transaction t = session.beginTransaction();
        String shql = "select s from " + Share.class.getName() + " s where s.date = ? and s.code = ?";
        String uhql = "update " + Share.class.getName() + " s set s.riseandfall = ? where s.date = ? and s.code = ?";
        for(Share share : shares){
            Query query = session.createQuery(shql);
            query.setParameter(0,share.getDate());
            query.setParameter(1,share.getCode());
            if(query.uniqueResult() != null){
                logger.info("数据库中已存在" + share.getCode() + ":" + share.getDate() + ", " + "正在更新");
                Query query1 = session.createQuery(uhql);
                query1.setParameter(0,share.getRiseandfall());
                query1.setParameter(1,share.getDate());
                query1.setParameter(2,share.getCode());
                query1.executeUpdate();
            }else {
                session.persist(share);
            }

        }
        t.commit();
        session.close();
    }
}
